package com.fubowen.lepton.extension

import android.net.Uri
import org.jsoup.Jsoup
import org.jsoup.nodes.Document

val regex =
    Regex("^[^\\p{IsAlphabetic}\\d\\p{IsHan}]+|[(（][^)）]*[)）]|[^\\p{IsAlphabetic}\\d\\p{IsHan}]+$")
const val agent =
    "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.210 Mobile Safari/537.36"

fun String?.toUrl() = this?.let { Uri.parse(this) }
fun String?.trimChar() = this?.let { regex.replace(it, "") }
fun String?.tryGetDocument(
    tryCount: Int = 3,
    timeout: Int = 30000,
    userAgent: String = agent,
    callback: (Boolean, Document?, String?) -> Unit
) {
    this?.let {
        var document: Document? = null
        var state = false
        var msg: String? = null
        for (i in 0 until tryCount) {
            try {
                document = Jsoup.connect(it)
                    .timeout(timeout)
                    .userAgent(userAgent)
                    .get()
                state = true
                break
            } catch (e: Exception) {
                msg = e.message
            }
        }
        callback(state, document, msg)
    }
}

inline fun <reified T> String?.toTarget(): T? {
    val value = when (T::class.java) {
        T::class.java -> this?.toIntOrNull()
        Double::class.java -> this?.toDoubleOrNull()
        String::class.java -> this
        Float::class.java -> this?.toFloatOrNull()
        Boolean::class.java -> this.toBoolean()
        Long::class.java -> this?.toLongOrNull()
        else -> throw java.lang.ClassCastException("不能识别的类型${T::class.java}")
    }
    return value as T?
}